<script setup>
import { ref } from 'vue'
import {
  articleAddChannelService,
  articleEditChannelService
} from '@/api/article.js'
// 弹框
const dialogVisible = ref(false)
const formRef = ref()

/*
 * 组件对外暴露一个方法 open，基于 open 传来的参数，区分添加还是编辑
 * open（{}）=>表单无需渲染，说明是添加
 * open（{id，cate_name，·..}）=>表单需要渲染，说明是编辑
 * open调用后，可以打开弹窗
 */
const open = (row) => {
  dialogVisible.value = true
  channelCategoryModel.value = { ...row }
}

// 表单模型
const channelCategoryModel = ref({
  cate_name: '',
  cate_alias: ''
})

// 表单校验规则
const rules = ref({
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的字母数字',
      trigger: 'blur'
    }
  ]
})

// 提交表单
const emit = defineEmits(['success'])
const onSubmit = async () => {
  await formRef.value.validate()
  // 判断是编辑还是添加
  const isEdit = channelCategoryModel.value.id
  // 编辑
  if (isEdit) {
    await articleEditChannelService(channelCategoryModel.value)
    ElMessage.success('分类编辑成功！')
  }
  // 添加
  else {
    await articleAddChannelService(channelCategoryModel.value)
    ElMessage.success('分类添加成功！')
  }
  dialogVisible.value = false
  // 改动成功通知父组件刷新
  emit('success')
}

defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="channelCategoryModel.id ? '编辑分类' : '添加分类'"
    width="500"
  >
    <el-form
      :model="channelCategoryModel"
      :rules="rules"
      ref="formRef"
      style="margin-top: 20px"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input
          v-model="channelCategoryModel.cate_name"
          placeholder="请输入分类名称"
          minlength="1"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input
          v-model="channelCategoryModel.cate_alias"
          placeholder="请输入分类别名"
          minlength="1"
          maxlength="15"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteCategory">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
